package com.example.myapplication;

import android.content.Context;
import android.widget.Toast;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class UserInfoIO {
    public static boolean storeUser(String username, String password, Context context) {
        FileOutputStream fos_name=null;
        FileOutputStream fos_password=null;
        try {
            fos_name=context.openFileOutput("userNameData.txt",Context.MODE_APPEND);
            fos_password=context.openFileOutput("passwordData.txt",Context.MODE_APPEND);
            String msg_name=username+"!";
            fos_name.write(msg_name.getBytes());
            String msg_password=password+"!";
            fos_password.write(msg_password.getBytes());
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        finally {
            try {
                fos_password.close();
                fos_name.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static Map<String,String> loadUser(Context context) {
        FileInputStream fis_name=null;
        FileInputStream fis_password=null;
        try {
            fis_name=context.openFileInput("userNameData.txt");
            fis_password=context.openFileInput("passwordData.txt");
            byte[] msg_name=new byte[fis_name.available()];
            byte[] msg_password=new byte[fis_password.available()];
            fis_name.read(msg_name);
            fis_password.read(msg_password);
            String username=new String(msg_name);
            String password=new String(msg_password);
            String[] allName=username.split("!");
            String[] allPassword=password.split("!");
            Map<String,String> userMap=new HashMap<>();
            for(int i=0;i<allName.length;i++)
            {
                userMap.put(allName[i],allPassword[i]);
                System.out.println(allName[i]+"   "+allPassword[i]);
            }
            return userMap;

        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        finally {
            try {
                fis_name.close();
                fis_password.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
